package com.kfpanda.search.index;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;

import com.util.common.encoding.FileCode;

/**
 * <b>ClassName:<b> AbstractFileDocument
 * <br><b>Description: <br>
 * TODO
 * @Author: kfpanda
 * @Date：2012-1-8 下午04:07:18
 * @ModifyUser：shapecool
 *
 */
public abstract class AbstractFileDocument implements FileDocumentor{
	
	private Logger logger = Logger.getLogger(AbstractFileDocument.class);
	
	/**
	 * <b>Description: <br>
	 * Makes a document for a File.
	    <p>
	    The document has three fields:
	    <ul>
	    <li><code>path</code>--containing the pathname of the file, as a stored,
	    untokenized field;
	    <li><code>modified</code>--containing the last modified date of the file as
	    a field as created by <a
	    href="lucene.document.DateTools.html">DateTools</a>; and
	    <li><code>contents</code>--containing the full contents of the file, as a
	    Reader field;
	 * @param writer
	 * @param file
	 * @throws IOException
	 * @Author: kfpanda
	 * @ModifyUser：kfpanda
	 * @Date：2012-1-8 下午04:09:25
	 */
	public Document document(File f) {

		if (f.isHidden() || !f.exists() || !f.canRead()) {
			return null;
		}
		
		System.out.println("Indexing " + f.getPath());
		
		Document doc = new Document();
		
		doc.add(new Field("filePath", f.getPath(), Field.Store.YES,
				Field.Index.NOT_ANALYZED));
		doc.add(new Field("fileName", f.getName(), Field.Store.YES,
				Field.Index.NOT_ANALYZED));
		doc.add(new Field("lastModified", DateTools.timeToString(
						f.lastModified(), DateTools.Resolution.MINUTE),
							Field.Store.YES, Field.Index.NOT_ANALYZED));
		
		FileInputStream fis = null;
		String streamCode = "UTF-8";
		try {
			fis = new FileInputStream(f);
			streamCode = FileCode.guestStreamEncoding(fis);
			String stemp = fileReaderAll(f.getPath(), streamCode, 10);
			doc.add(new Field("intro", stemp, Field.Store.YES, Field.Index.ANALYZED));
			InputStreamReader isr = new InputStreamReader(fis, streamCode);
			doc.add(new Field("contents", isr));
		} catch (IOException e) {
			logger.error("文件（" + f.getPath() + "）读取异常", e);
		} finally{
			IOUtils.closeQuietly(fis);
		}
		
		return doc;
	}

}
